<template>
  <div>
    <el-form ref="form" label-width="80px" size="mini" class="my-form">
      <el-form-item label="统计周期">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="chartsInfo()"
        ></el-date-picker>（最大只能统计31天以内的数据）
        <el-button type="primary" plain @click="chartsInfo()" :loading="btn_loading">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-divider></el-divider> -->
    <div class="content" v-loading="loading" id="rbContent" v-show="DataShow">
      <div class="left" id="statistics_sharts" ref="chart"></div>
      <div></div>
      <div class="right">
        <ul style="margin:0;padding:0">
          <li>
            <span>总认证次数：</span>
            <b>{{all_authorize}}</b>
          </li>
          <li>
            <span>总领取次数：</span>
            <b>{{ all_num }}</b>
          </li>
          <li>
            <span>总领取金额：</span>
            <b class="text-danger">￥{{ all_amount }}</b>
          </li>
        </ul>
        <div class="rbTable">
          <el-table ref="rbTable" :data="lists" stripe height="600">
            <el-table-column prop="time" label="日期" width="80"></el-table-column>
            <el-table-column prop="authrizeNum" label="认证次数"></el-table-column>
            <el-table-column prop="people" label="领取次数"></el-table-column>
            <el-table-column prop="amount" label="领取金额">
              <template slot-scope="{ row }">
                <b class="text-danger">￥{{ row.amount }}</b>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div v-show="noDataShow" class="noDataShow">当前日期暂无交易</div>
  </div>
</template>

<script>
import "echarts/theme/macarons.js";
export default {
  components: {},
  watch: {},
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      loading: false, //红包统计图表数据加载状态
      form: {
        time: ["", ""]
      },
      all_amount: 0, // 总领取金额
      all_num: 0, // 总领取次数
      all_authorize: 0, //总认证次数
      btn_loading: false,
      lists: [],
      option: {
        title: {
          text: "认证次数/领取次数/领取金额统计",
          textStyle: {
            color: "#000",
            fontSize: 16
          }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ["认证次数", "领取次数", "领取金额"] //统计的数据（认证次数，领取次数，领取金额）
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            //x轴字体颜色
            axisLine: {
              lineStyle: {
                color: "#000"
              }
            },
            splitLine: {
              show: false //隐藏网格
            },
            data: [], //x轴的数据
            axisPointer: {
              type: "shadow",
              shadowStyle: {
                // 阴影指示器样式设置
                color: "rgba(1,127,90,0.1)" // 阴影颜色
              },
              splitLine: {
                show: false //隐藏网格
              },
              splitArea: {
                show: false //隐藏网格
              }
            },
            axisLabel: {
              show: true
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            x: "center",
            name: "（认证次数/领取次数）",
            min: 0,
            // max: 100,
            show: true,
            //y轴颜色
            axisLine: {
              lineStyle: {
                color: "#000"
              }
            },
            splitLine: {
              show: true //隐藏网格
            },
            splitArea: {
              show: false //隐藏网格背景
            }
          },
          {
            type: "value",
            name: "（领取金额）",
            x: "center",
            show: true,
            min: 0,
            // max: 100,
            //y轴颜色
            splitLine: {
              show: false //隐藏网格
            },
            splitArea: {
              show: false //隐藏网格背景
            },
            axisLine: {
              lineStyle: {
                color: "#000"
              }
            }
          }
        ],
        series: [] //图表的数据
      },
      noDataShow: false,
      DataShow: true
    };
  },
  methods: {
    //加载红包统计数据
    chartsInfo() {
      if (this.form.time == null || this.form.time[0] == "") {
        this.$message.error("请选择日期参数！");
        return false;
      } else {
        let startTime = new Date(this.form.time[0]).getTime();
        let endTime = new Date(this.form.time[1]).getTime();
        if (Number((endTime - startTime) / (3600 * 1000 * 24)) > 31) {
          this.$message.error(
            "最大只能统计31天以内的数据，请重新选择时间范围！"
          );
          return false;
        }
      }

      this.loading = true;
      this.option.series = [];
      this.noDataShow = false;
      this.DataShow = true;
      this.btn_loading = true;
      this.$axios
        .get(`/admin/statistical_draw/`, {
          params: {
            time_min: this.form.time[0],
            time_max: this.form.time[1]
          }
        })
        .then(res => {
          var amountData = []; //领取金额
          var timeData = []; //时间
          var numData = []; //领取次数
          var authorizeData = []; //认证次数

          this.all_amount = res.all_amount; //总领取金额
          this.all_num = res.all_num; //总领取次数
          this.all_authorize = res.all_authorize; //总认证次数

          this.option.xAxis[0].data = res.xAxis; //x轴的数据：日期
          timeData = res.xAxis;
          // this.option.legend.data = [];

          // for (const i of res.num_arr) {
          //   this.option.legend.data.push(i.name);
          // }
          // this.option.legend.data.push(res.amount_arr[0].name);

          console.log(this.option);
          //认证次数-折线图
          for (let i = 0; i < res.authorize_arr.length; i++) {
            authorizeData = res.authorize_arr[i].data;
            this.option.series.push({
              name: "认证次数",
              type: "line", //设置图表的类型：line：折线图；bar：柱状图
              smooth: true, //让曲线平滑
              yAxisIndex: 0, // 认证次数用的第一个y轴
              color: "#017f5a", //设置折线图的颜色
              data: res.authorize_arr[i].data, //折线图的数据
              itemStyle: {
                normal: {
                  label: {
                    show: true, //开启数值显示
                    textStyle: {
                      //数值样式
                      color: "#017f5a", //数值的颜色
                      fontSize: 12
                    }
                  },
                  lineStyle: {
                    width: 2 // 设置折线图线条的粗细
                  }
                }
              }
            });
          }

          //领取次数-折线图
          for (let i = 0; i < res.num_arr.length; i++) {
            numData = res.num_arr[i].data;
            this.option.series.push({
              name: "领取次数",
              type: "line",
              yAxisIndex: 0, // 领取次数用的第一个y轴
              data: res.num_arr[i].data,
              // stack: 'bar', // 柱状图叠加
              color: "#ff7e00",
              itemStyle: {
                // 柱状图悬停颜色
                emphasis: {
                  // 普通图表的高亮颜色
                  // color: color[j],
                  // 地图区域的高亮颜色
                  // areaColor: "blue"
                },
                normal: {
                  label: {
                    show: true, //开启数值显示
                    textStyle: {
                      //数值样式
                      color: "#ff7e00",
                      fontSize: 12
                    }
                  }
                }
              }
            });
          }

          //领取金额-柱状图
          for (let i = 0; i < res.amount_arr.length; i++) {
            amountData = res.amount_arr[i].data;
            this.option.series.push({
              name: "领取金额",
              type: "bar",
              barWidth: 20,
              smooth: true, //让曲线平滑
              yAxisIndex: 1, //领取金额用的第二个y轴
              color: "#d8d8d8",
              data: res.amount_arr[i].data,
              itemStyle: {
                normal: {
                  label: {
                    show: true, //开启数值显示
                    textStyle: {
                      //数值样式
                      color: "#000",
                      fontSize: 12
                    },
                    //改变数值显示的格式，金额前面加￥
                    formatter: function(value) {
                      return "￥" + value.data;
                    }
                  }
                }
              }
            });
          }

          //右侧列表展示：将日期、领取金额、领取次数数组的数据组合成一个数组对象
          this.lists = amountData.map((item, index) => ({
            time: timeData[index],
            authrizeNum: authorizeData[index],
            people: numData[index],
            amount: amountData[index]
          }));

          var chartDom = this.$refs.chart;
          var myChart = this.$echarts.init(chartDom, "macarons"); //初始化echarts实例
          myChart.setOption(this.option, true); //设置为true的话，就是notMerge，不合并；false的话，就Merge，之前的东西还保留~
        })
        .catch(err => {
          this.all_authorize = 0;
          this.all_amount = 0;
          this.all_num = 0;
          if (err.response) {
            this.$message.error(
              err.response.data.error || err.response.data.detail
            );
            if (err.response.data.error == "当前日期暂无交易") {
              this.noDataShow = true;
              this.DataShow = false;
            }
          }
        })
        .finally(() => {
          this.btn_loading = false;
          this.loading = false;
        });

      this.$emit("chartsInfo");
    },

    // 时间戳转日期
    formatDate(value) {
      if (value != null) {
        let date = new Date(value);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? "0" + MM : MM;
        let d = date.getDate();
        d = d < 10 ? "0" + d : d;
        let h = date.getHours();
        h = h < 10 ? "0" + h : h;
        let m = date.getMinutes();
        m = m < 10 ? "0" + m : m;
        let s = date.getSeconds();
        s = s < 10 ? "0" + s : s;
        return y + "-" + MM + "-" + d;
      } else {
        value = "";
      }
    }
  },
  created() {
    //初始化统计周期为一个月
    let date = new Date();
    let startTime = date.getTime() - 3600 * 1000 * 24 * 30;
    this.form.time[0] = this.formatDate(startTime);
    this.form.time[1] = this.formatDate(date);
    //this.chartsInfo();
  },
  updated() {
    //解决table设置固定高度后，汇总不显示问题
    // this.$nextTick(() => {
    //   this.$refs.rbTable.doLayout();
    // });
  }
};
</script>

<style scoped lang="scss">
.content /deep/ .el-table th.is-leaf,
.content /deep/ .el-table .cell {
  text-align: center;
}
.my-tabs {
  .detailsTop {
    position: relative;
    .btnRight {
      position: absolute;
      right: 0;
      z-index: 999;
      top: 0;
    }
    b {
      display: inline-block;
      margin-right: 5px;
      font-size: 18px;
    }
  }
}
.my-tabs /deep/ .el-form-item {
  margin-bottom: 0px;
}
.rbTable /deep/ .el-table td {
  padding: 4px 0;
}
.rbTable /deep/ .el-table__footer .has-gutter tr td {
  font-size: small;
  font-weight: bold;
  color: #f56c6c !important;
}

.msg-box {
  float: left;
  line-height: 48px;
  margin-left: 20px;
}
label {
  display: inline-block;
  width: 150px;
  text-align: right;
}
// span {
//   padding-left: 20px;
// }
.msg-box /deep/ .img {
  margin-left: 20px;
}
.content {
  display: flex;
  margin-top: 30px;
  .left {
    flex: 7;
    // border-right: 1px solid gray;
  }
  #statistics_sharts {
    width: 1200px;
    height: 700px;
  }
  .right {
    overflow: auto;
    flex: 3;
    li {
      line-height: 32px;
      font-weight: 900;
      color: #606266;
      list-style: none;
      span {
        margin-right: 5px;
        display: inline-block;
        width: 100px;
        text-align: right;
      }
    }
  }
}
.noDataShow {
  height: 500px;
  line-height: 500px;
  text-align: center;
}
@media screen and (max-width: 1470px) {
  .content {
    display: block;
    #statistics_sharts {
      width: 1000px;
      height: 700px;
    }
  }
}
</style>